package com.huiyang.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.huiyang.demo.entity.DeviceInfoEntity;
import com.huiyang.demo.service.IWebSocketResponseListener;
import com.huiyang.demo.service.WebSocketUtil;
import com.huiyang.demo.utils.BCGArrayList;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, IWebSocketResponseListener {

    /**
     * 图表
     */
    private LineChart heartChart, breatheChart;
    private RelativeLayout rlChartHeart, rlBreatheHeart;
    private EditText etId;
    private Button btnStart, btnEnd;
    private TextView tvStatus;
    private TextView tvTemp, tvBedStatus, tvBreathRate, tvBreathRateStable, tvHeartRate, tvHeartRateStable, tvSnoreRate, tvSnoreTime;

    /**
     * websocket帮助类
     */
    private WebSocketUtil webSocketUtil;
    Handler dispatchHandler = new Handler();

    private int currentIndex = 0;//数据index
    private int MAX_NUMBER = 440;//图表心跳集合的最大size
    private int MAX_NUMBER_B = MAX_NUMBER / 11;//图表呼吸集合的最大size
    private BCGArrayList heartList = new BCGArrayList();//心跳数据
    private BCGArrayList breathList = new BCGArrayList();//呼吸数据
    private  BCGArrayList cacheList = new BCGArrayList();//缓存服务器的数据
    private BCGArrayList cacheList2 = new BCGArrayList();//缓存数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rlChartHeart = findViewById(R.id.rl_chart_heart);
        rlBreatheHeart = findViewById(R.id.rl_chart_breathe);
        etId = findViewById(R.id.et_id);
        btnStart = findViewById(R.id.btn_start);
        btnEnd = findViewById(R.id.btn_end);
        tvStatus = findViewById(R.id.tv_status);

        tvTemp = findViewById(R.id.tv_temp);
        tvBedStatus = findViewById(R.id.tv_bed_status);
        tvBreathRate = findViewById(R.id.tv_breath_rate);
        tvBreathRateStable = findViewById(R.id.tv_breath_rate_stable);
        tvHeartRate = findViewById(R.id.tv_heart_rate);
        tvHeartRateStable = findViewById(R.id.tv_heart_rate_stable);
        tvSnoreRate = findViewById(R.id.tv_sonre_rate);
        tvSnoreTime = findViewById(R.id.tv_sonre_time);

        btnStart.setOnClickListener(this);
        btnEnd.setOnClickListener(this);
        addChartView();
        webSocketUtil = WebSocketUtil.getInstance(this);
    }

    /**
     * 初始化图表
     */
    private void addChartView() {
        heartChart = new LineChart(this);
        breatheChart = new LineChart(this);
        setChart(heartChart);
        setChart(breatheChart);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rlChartHeart.addView(heartChart, params);
        rlBreatheHeart.addView(breatheChart, params);
    }

    /**
     * 设置 LineChart 参数
     *
     * @param chart
     */
    private void setChart(LineChart chart) {
        chart.setDrawGridBackground(false);
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(false);
        chart.setDragEnabled(false);
        chart.setScaleEnabled(false);
        chart.setPinchZoom(false);
        chart.getAxisLeft().setDrawGridLines(false);
        chart.getAxisRight().setEnabled(false);
        chart.getXAxis().setEnabled(false);

        chart.getAxisLeft().setAxisMaximum(600);
        chart.getAxisLeft().setAxisMinimum(-600);

        chart.getAxisLeft().setEnabled(false);
        chart.invalidate();
    }

    LineDataSet set1, set2;

    /**
     * 给 LineChart 赋值
     *
     * @param heart
     * @param breath
     */
    private void setData(ArrayList<Entry> heart, ArrayList<Entry> breath) {
        try {
            if (heartChart == null || breatheChart == null)
                return;
            if (heartChart.getData() != null &&
                    heartChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) heartChart.getData().getDataSetByIndex(0);
                set2 = (LineDataSet) breatheChart.getData().getDataSetByIndex(0);
                set1.setValues(heart);
                set2.setValues(breath);
                set1.notifyDataSetChanged();
                set2.notifyDataSetChanged();
                heartChart.getData().notifyDataChanged();
                breatheChart.getData().notifyDataChanged();
                heartChart.notifyDataSetChanged();
                breatheChart.notifyDataSetChanged();
            } else {
                heartChart.setData(setLineData(heart, 1));
                breatheChart.setData(setLineData(breath, 2));

                setLegend(heartChart);
                setLegend(breatheChart);
            }

            heartChart.invalidate();
            breatheChart.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置LineChart颜色
     *
     * @param dataList
     * @param type
     * @return
     */
    private LineData setLineData(ArrayList<Entry> dataList, int type) {//type 1 心跳，2 呼吸
        LineDataSet set = new LineDataSet(dataList, "DataSet 1");
        switch (type) {
            case 1:
                set.setColor(Color.RED);
                break;
            case 2:
                set.setColor(Color.BLUE);
                break;
            default:
                break;
        }
        set.setLineWidth(0.7f);
        set.setDrawValues(false);
        set.setDrawCircles(false);
        set.setMode(LineDataSet.Mode.LINEAR);
        set.setDrawFilled(false);
        return new LineData(set);
    }

    /**
     * 设置LineChart字体
     *
     * @param chart
     */
    private void setLegend(LineChart chart) {
        Typeface tfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
        // get the legend (only possible after setting data)
        Legend l = chart.getLegend();
        l.setEnabled(false);
        // get the legend (only possible after setting data)
        l.setForm(Legend.LegendForm.LINE);
        l.setTypeface(tfLight);
        l.setTextSize(11f);
        l.setTextColor(Color.WHITE);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
    }


    private int socketType = 0;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                //开始连接
                String id = etId.getText().toString();
                if (TextUtils.isEmpty(id)) {
                    Toast.makeText(this, "请输入设备编号", Toast.LENGTH_LONG).show();
                    break;
                }
                if (socketType != 1) {//防止重复连接
                    socketType = 1;
                    //开启websocket连接
                    webSocketUtil.startSocket(this, id);
                    //开启线程
                    dispatchHandler.postDelayed(sendDataRunnable, 165);
                    initBCG();
                }
                break;
            case R.id.btn_end:
                //断开websocket连接
                webSocketUtil.closeSocket();
                //关闭线程
                dispatchHandler.removeCallbacks(sendDataRunnable);
                socketType = 2;
                break;
            default:
                break;

        }
    }

    @Override
    public void onMessageText(DeviceInfoEntity text) {
        if (text != null) {
            if (text.getMsgType().equals("DeviceInfo")) {
                /**
                 * 设备信息数据
                 */
                tvTemp.setText(text.getTemperature());
                tvBedStatus.setText(text.getBedStatus());
                tvBreathRate.setText(text.getBreatheRate());
                tvBreathRateStable.setText(text.getBreatheRateStable());
                tvHeartRate.setText(text.getHeartRate());
                tvHeartRateStable.setText(text.getHeartRateStable());
                tvSnoreRate.setText(text.getSnoreRate());
                tvSnoreTime.setText(text.getSnoreTime());
            } else if (text.getMsgType().equals("ChartData")) {
                /**
                 * 设备波形数据
                 */
                cacheList.addAll(text.getEcgList());
            }
        }
    }

    @Override
    public void onSocketStatus(String status) {
        //web socket连接状态
        tvStatus.setText(status);
    }


    /**
     * 初始化Ecg
     */
    private void initBCG() {
        currentIndex = 0;
        heartList.clear();
        breathList.clear();
        for (int i = 0; i < MAX_NUMBER; i++) {
            heartList.add(new Entry(currentIndex, 0));
            if (i % 11 == 0) {
                breathList.add(new Entry(currentIndex, 0));
            }
            currentIndex++;
        }
        setData(heartList,breathList);
    }

    /**
     * 画图表
     * @param count
     */
    private synchronized void showBCGCache(int count) {
        for (int i = 0; i < count; i++) {
            if (!(cacheList2.size() > 0))
                return;
            if (cacheList2.get(0).getX() != 9999)
                heartList.add(new Entry(currentIndex, cacheList2.get(0).getX()));
            if (cacheList2.get(0).getY() != 9999)
                breathList.add(new Entry(currentIndex, cacheList2.get(0).getY()));
            currentIndex++;
            cacheList2.remove(0);
        }


        if (heartList.size() > MAX_NUMBER)
            heartList.removeRange(0, heartList.size() - MAX_NUMBER);
        if (breathList.size() > MAX_NUMBER_B)
            breathList.removeRange(0, breathList.size() - MAX_NUMBER_B);


        setData(heartList,breathList);

    }

    private Runnable sendDataRunnable = new Runnable() {
        @Override
        public void run() {
            cacheList2.addAll(cacheList);
            cacheList.clear();
            if (cacheList2.size() > 200) {
                if (cacheList2.size() > MAX_NUMBER) {
                    showBCGCache(66);
                } else {
                    showBCGCache(22);
                }

            }
            dispatchHandler.postDelayed(this, 165);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webSocketUtil.unbind();
    }
}